//
//  AppDelegate.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/6/6.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "AppDelegate.h"
#import "RootViewController.h"
#import "WelcomeViewController.h"
#import "LoginViewController.h"
//#import <AMapFoundationKit/AMapFoundationKit.h>
#import "APIKey.h"
#import "WKProgressHUD.h"
//#import <MAMapKit/MAMapKit.h>
//#import <AMapLocationKit/AMapLocationKit.h>
#define LocationTimeout 10
#define ReGeocodeTimeout 5
#import "Common.h"
#import "UMMobClick/MobClick.h"
//#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#import "SSKeychain.h"
//待接单
#import "ReceiveViewController.h"
//执行中
#import "MissionViewController.h"
//司机认证
#import "PerfectCarInfoVC1.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif



@interface AppDelegate ()
//<JPUSHRegisterDelegate>

{
    RootViewController *rootVC;
    Reachability *hostReach;//试试监听网络变化
    UIImageView * viewImage ;
    Common * com;
    NSTimer * timer;
    
}
//@property (nonatomic,strong) CLGeocoder *geoC;
@property (nonatomic,strong) NSMutableDictionary * dicUrl;
@property (nonatomic,strong) WelcomeViewController *welcomeVC;
@property (nonatomic,strong) LoginViewController *loginVC;
//@property (nonatomic,strong) AMapLocationManager *locationManager;
//@property (nonatomic,copy) AMapLocatingCompletionBlock completionBlock;
@property (nonatomic,copy) NSString *uuidString;
//@property (nonatomic, strong) BMKGeoCodeSearch *geoCode;        // 地理编码

@property (nonatomic, assign) CGFloat longitude;  // 经度

@property (nonatomic, assign) CGFloat latitude; // 纬度

@end

@implementation AppDelegate

- (void)configureAPIKey
{
    if ([APIKey length] == 0)
    {
//        NSString *reason = [NSString stringWithFormat:@"apiKey为空，请检查key是否正确设置。"];
        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:reason delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
//        [alert show];
    }
    
//    [AMapServices sharedServices].apiKey = (NSString *)APIKey;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = WhiteColor;
    com = [[Common alloc]init];

    
//    [self startLocation];
    

    [self createRooVC];
    [self chooseRootVC];
//    [self configLocationManager];

//   if (launchOptions)
//        {
//            
//[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
//            NSDictionary *userInfo = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
//[self presentViewControllerWithUserInfo:userInfo];
//            }
//       
    [self.window makeKeyAndVisible];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    
    //添加全局网络监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    
    hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    
    [hostReach startNotifier]; //开始监听,会启动一个run loop
    

    [self configureAPIKey];
    //友盟统计
    UMConfigInstance.appKey = @"5861c8569f06fd4dcc000539";
    UMConfigInstance.channelId = @"App Store";
//    UMConfigInstance.eSType = E_UM_GAME; //仅适用于游戏场景，应用统计不用设置
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *string = [userDefaults objectForKey:@"login_token"];
    
    if (string != nil) {
        [self checkUserToken];
        
    }
//    [self JPUSHService:launchOptions];
    _dicUrl = [[NSMutableDictionary alloc]init];
    [_dicUrl setObject:@"" forKey:@"city"];
    [_dicUrl setObject:@"" forKey:@"latitude"];
    [_dicUrl setObject:@"" forKey:@"longitude"];
    [_dicUrl setObject:@"" forKey:@"county"];
    [_dicUrl setObject:@"" forKey:@"address"];
    [_dicUrl setObject:@"" forKey:@"province"];
    

//    [self turnOnTimer];
    
    
    
    return YES;
}

/*
-(void)startLocation{
    
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"IGhnse2DrIj80pBfccybkz2X0bGkxig0"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    

    
}

#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
//    NSLog(@"heading is %@",userLocation.heading);
}

//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//    NSLog(@"当前位置信息：didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    self.longitude = userLocation.location.coordinate.longitude;
    self.latitude = userLocation.location.coordinate.latitude;
    NSString * latitude = [NSString stringWithFormat:@"%f",self.latitude];
    NSString * longitude = [NSString stringWithFormat:@"%f",self.longitude];

    [_dicUrl setObject:latitude forKey:@"latitude"];
    [_dicUrl setObject:longitude forKey:@"longitude"];

    [self outputAdd];
    // 当前位置信息：didUpdateUserLocation lat 23.001819,long 113.341650
}

#pragma mark geoCode的Get方法，实现延时加载
- (BMKGeoCodeSearch *)geoCode
{
    if (!_geoCode)
    {
        _geoCode = [[BMKGeoCodeSearch alloc] init];
        _geoCode.delegate = self;
    }
    return _geoCode;
}

//#pragma mark 获取地理位置按钮事件
- (void)outputAdd
{
    // 初始化反地址编码选项（数据模型）
    BMKReverseGeoCodeOption *option = [[BMKReverseGeoCodeOption alloc] init];
    // 将数据传到反地址编码模型
    option.reverseGeoPoint = CLLocationCoordinate2DMake(self.latitude, self.longitude);
//    NSLog(@"%f - %f", option.reverseGeoPoint.latitude, option.reverseGeoPoint.longitude);
    // 调用反地址编码方法，让其在代理方法中输出
    [self.geoCode reverseGeoCode:option];
}


#pragma mark 代理方法返回反地理编码结果
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (result) {
        //        self.address.text = [NSString stringWithFormat:@"%@", result.address];
//        NSLog(@"位置结果是：%@ - %@", result.address, result.addressDetail.city);

        NSString * province = [NSString stringWithFormat:@"%@",result.addressDetail.province];
        NSString * city = [NSString stringWithFormat:@"%@",result.addressDetail.city];
        //区县名称
        NSString * district = [NSString stringWithFormat:@"%@",result.addressDetail.district];
        NSString * address = [NSString stringWithFormat:@"%@",result.address];
        
        [_dicUrl setObject:province forKey:@"province"];
        [_dicUrl setObject:city forKey:@"city"];
//        [_dicUrl setObject:@"" forKey:@"latitude"];
//        [_dicUrl setObject:@"" forKey:@"longitude"];
        [_dicUrl setObject:district forKey:@"county"];
        [_dicUrl setObject:address forKey:@"address"];
//        latitude	纬度	BigDecimal	Y
//        longitude	经度	BigDecimal	Y
//        province	省名称	String	N
//        city	市名称	String	N
//        county	区县	String	N
//        address	详细地址	String	Y
//        
        
        //        NSLog(@"经纬度为：%@ 的位置结果是：%@", locationString, result.address);
//        self.currentCityString = result.addressDetail.city;
        
//        [self.cityButton setTitle:self.currentCityString forState:UIControlStateNormal];
        // 定位一次成功后就关闭定位
//        [_locService stopUserLocationService];
        
    }else{
        NSLog(@"%@", @"找不到相对应的位置");
    }
    
}

//#pragma mark 代理方法返回地理编码结果
//- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
//{
//    if (result) {
//        NSString *locationString = [NSString stringWithFormat:@"经度为：%.2f   纬度为：%.2f", result.location.longitude, result.location.latitude];
//        NSLog(@"经纬度为：%@ 的位置结果是：%@", locationString, result.address);
//        //        NSLog(@"%@", result.address);
//    }else{
//        //        self.location.text = @"找不到相对应的位置";
//        NSLog(@"%@", @"找不到相对应的位置");
//    }
//}
//
 
 */

/*
-(void)turnOnTimer{
    //14400.0 秒调用一次
    timer = [NSTimer scheduledTimerWithTimeInterval:1800 target:self selector:@selector(pushGPSdata) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}


-(void)pushGPSdata{
    
    NSString * cityName = [NSString stringWithFormat:@"%@",_dicUrl[@"city"]];
    NSString * latitude = [NSString stringWithFormat:@"%@",_dicUrl[@"latitude"]];
    NSString * longitude = [NSString stringWithFormat:@"%@",_dicUrl[@"longitude"]];
    
    if (cityName.length !=0&&latitude.length !=0&&longitude.length !=0) {
        [self pushGPS:_dicUrl];
    }
}
-(void)pushGPS:(NSMutableDictionary*)dicDate{
    
    

//    NSLog(@"上传%@",[NSString stringWithFormat:@"latitude:%@longitude:%@",dicDate[@"latitude"],dicDate[@"longitude"]]);
    NSLog(@"dicDate=====%@",dicDate);
    [com afPostRequestWithUrlString:trail_Url parms:dicDate finishedBlock:^(id responseObj) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dic[@"message"]);
        NSString * userStatus = [NSString stringWithFormat:@"%@",dic[@"success"]];
        if ([userStatus isEqualToString:@"1"]) {
            NSLog(@"GPS成功");
        }else{
            NSLog(@"GPS失败");
        }
    } failedBlock:^(NSString *errorMsg) {
    }];
}
*/

/*

-(void)JPUSHService:(NSDictionary*)launchOptions{
    
//    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    //获取uuid
    [self sendUUID];

    
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
            NSString *strUrl = [self.uuidString stringByReplacingOccurrencesOfString:@"-" withString:@""];
            NSLog(@"uuidString:%@",strUrl);

            [JPUSHService setAlias:strUrl  callbackSelector:nil object:nil];
        }//7C3129208DB44A399BDCAEF0729AA780
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];

}
- (void)networkDidLogin:(NSNotification *)notification {
    
    
    if ([JPUSHService registrationID]) {
        NSLog(@"get RegistrationID:%@",[JPUSHService registrationID]);//获取registrationID
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:[JPUSHService registrationID] forKey:@"pushid"];
    }
}
 
 */

-(void)application:(UIApplication *)application didReceiveLocalNotification:(nonnull UILocalNotification *)notification{
    
//    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    
    
}


-(WelcomeViewController *)welcomeVC
{
    if (!_welcomeVC) {
        _welcomeVC = [[WelcomeViewController alloc]init];
        __weak typeof(self) weakSelf = self;
        
        _welcomeVC.callBack = ^(){
            [weakSelf chooseRootVC];
        };
    }
    return _welcomeVC;
}

-(void)createRooVC
{
    rootVC = [RootViewController defaultsTabBar];;
    
}

-(void)chooseRootVC
{
//    BOOL flag = [[NSUserDefaults standardUserDefaults]boolForKey:@"firstIn"];
    
    
//    if (flag == YES) {
//        
//        self.window.rootViewController = rootVC;
//        
//    } else {
//        
//        self.window.rootViewController = self.welcomeVC;
//    }
    
    self.window.rootViewController = rootVC;

    
}


//监听到网络状态改变
- (void) reachabilityChanged: (NSNotification* )note

{
    
    Reachability* curReach = [note object];
    
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    
    [self updateInterfaceWithReachability: curReach];
    
}


//处理连接改变后的情况
- (void) updateInterfaceWithReachability: (Reachability*) curReach

{
    //对连接改变做出响应的处理动作。
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if(status == NotReachable)
    {
        [WKProgressHUD popMessage:@"网络异常，请检查网络配置" inView:self.window duration:1.5 animated:YES];
        
        //      UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil
        //                                                     message:@"网络异常，请检查网络设置"
        //                                                    delegate:nil
        //                                           cancelButtonTitle:@"确认" otherButtonTitles:nil];
        //      [alert show];
        
    }
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    //控制定时器不被kill
    UIApplication * app = [UIApplication sharedApplication];
    __block UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid) {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid) {
                bgTask = UIBackgroundTaskInvalid ;
            }
        });
    });
    

    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970] * 1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSDictionary *dic = @{@"time":timeString};
    
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"background" object:nil userInfo:dic];
    viewImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, Main_height)];
    viewImage.image = [UIImage imageNamed:@"startpage"];
    [self.window addSubview:viewImage];
    //极光推送
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //开始持续定位
//    self.locationManager.distanceFilter = 100.0;
//    [self.locationManager startUpdatingLocation];
    
//    self.locationManager.reGeocodeTimeout = 60;

    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
//    [self.locationManager stopUpdatingLocation];
    
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970] * 1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSDictionary *dic = @{@"time":timeString};
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"foreground" object:nil userInfo:dic];
    [self performSelector:@selector(delayMethod) withObject:nil afterDelay:1];
    
    [_dicUrl setObject:@"" forKey:@"city"];
    [_dicUrl setObject:@"" forKey:@"latitude"];
    [_dicUrl setObject:@"" forKey:@"longitude"];
    [_dicUrl setObject:@"" forKey:@"county"];
    [_dicUrl setObject:@"" forKey:@"address"];
    [_dicUrl setObject:@"" forKey:@"province"];

    
//    [self initCompleteBlock];
//    [self reGeocodeAction];
    //    configLocation
    NSNotification * Location = [NSNotification notificationWithName:@"configLocation" object:nil ];
    [[NSNotificationCenter defaultCenter] postNotification:Location];
    
    //极光
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    

}



-(void)AddrDesc{
    
    [com afPostRequestWithUrlString:trail_Url parms:_dicUrl finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        NSString * userStatus = [NSString stringWithFormat:@"%@",dic[@"success"]];
        if ([userStatus isEqualToString:@"1"]) {
            NSLog(@"GPS成功");
        }else{
            NSLog(@"GPS失败");
        }
    } failedBlock:^(NSString *errorMsg) {
    }];
}

//
//- (void)initCompleteBlock
//{
//    __weak AppDelegate *wSelf = self;
//    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
//    {
//
//        if (location){
//            if (regeocode){
//                [wSelf.dicUrl setObject:[NSString stringWithFormat:@"%f",location.coordinate.latitude] forKey:@"latitude"];
//                [wSelf.dicUrl setObject:[NSString stringWithFormat:@"%f",location.coordinate.longitude] forKey:@"longitude"];
//                if (regeocode.city == nil) {
//                    regeocode.city = @"";
//                }
//                if (regeocode.province == nil) {
//                    regeocode.province = @"";
//                }
//                if (regeocode.district == nil) {
//                    regeocode.district = @"";
//                }
//                if (regeocode.formattedAddress == nil) {
//                    regeocode.formattedAddress = @"";
//                }
//
//                NSString * address = [NSString stringWithFormat:@"%@%@",regeocode.province,regeocode.city];
//                NSString * citycode = [NSString stringWithFormat:@"%@",regeocode.citycode];
//                NSString * formattedAddress = [NSString stringWithFormat:@"%@",regeocode.formattedAddress];
//
//                [wSelf.dicUrl setObject:address forKey:@"cityName"];
//                [wSelf.dicUrl setObject:citycode forKey:@"cityCode"];
//                [wSelf.dicUrl setObject:formattedAddress forKey:@"addr"];
//
//                [wSelf AddrDesc];
//            }
//            else{
//                NSLog(@"%@",error.localizedDescription);
//            }
//        }
//    };
//}
//


/*

-(void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location{
    
//    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    // 容错
    if(location.coordinate.latitude == 0)
    return;
    
    // 获取用户输入的经纬度
    double latitude = location.coordinate.latitude ;
    double longitude = location.coordinate.longitude;
    [self initCompleteBlock];
    CLLocation *Location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    NSMutableDictionary * dicUrl = [[NSMutableDictionary alloc]init];
    // 反地理编码(经纬度---地址)
    [self.geoC reverseGeocodeLocation:Location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if(error == nil)
        {
            CLPlacemark *pl = [placemarks firstObject];
            NSString * latitude = [NSString stringWithFormat:@"%f",pl.location.coordinate.latitude];
            NSString * longitude = [NSString stringWithFormat:@"%f",pl.location.coordinate.longitude];
//            NSLog(@"%@",pl.thoroughfare);
//            NSLog(@"%@",pl.name);
//            NSLog(@"%@",pl.locality);
//            NSLog(@"%@",pl.subLocality);
//
            NSString * stress = [NSString stringWithFormat:@"%@%@%@",pl.locality,pl.subLocality,pl.name];

            [_dicUrl setObject:pl.locality forKey:@"cityName"];
            
            [_dicUrl setObject:latitude forKey:@"latitude"];
            [_dicUrl setObject:longitude forKey:@"longitude"];
            [_dicUrl setObject:@"111111" forKey:@"cityCode"];
            [_dicUrl setObject:stress forKey:@"addr"];


        }else
        {
            NSLog(@"反地理编码错误");
        }
    }];
}
*/

-(void)delayMethod{
    
    [viewImage removeFromSuperview];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *string = [userDefaults objectForKey:@"login_token"];
    
    if (string != nil) {
        [self checkUserToken];
        
    }

}

-(void)checkUserToken
{
    [Common requestWithUrlString:token_check contentType:application_json finished:^(id responseObj) {
        
        if ([responseObj[@"success"] boolValue]) {
            
        } else {
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            
            //            NSString *string = [userDefaults objectForKey:@"login"];
            
            //    self.isLogin =
            
            [userDefaults setObject:nil forKey:@"login"];
            [userDefaults setObject:nil forKey:@"login_token"];

        }
        
    } failed:^(NSString *errorMsg) {
        
    }];
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
    return YES;
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [NSString stringWithFormat:@"%@", deviceToken];
    //    NSLog(@"Device Token%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);

//    [JPUSHService registerDeviceToken:deviceToken];
    
}


- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
//    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
    
    

    if (application.applicationState != UIApplicationStateActive)
         {
        [self presentViewControllerWithUserInfo:userInfo];

         }
    
}
- (void)presentViewControllerWithUserInfo:(NSDictionary *)userInfo{
    
    ReceiveViewController *messageCtl=[[ReceiveViewController alloc] init];

    [self.window.rootViewController presentViewController:messageCtl animated:YES completion:^{}];

    
}



- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
//    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
    
    completionHandler(UIBackgroundFetchResultNewData);
}


#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        
//        [rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
//        [rootViewController addNotificationCount];
        
        //tag:0   司机认证  1 待接单 2 执行中
        
        
        NSString * strTag = [NSString stringWithFormat:@"%@",userInfo[@"tag"]];

        ReceiveViewController *messageCtl=[[ReceiveViewController alloc] init];
        //7C3129208DB44A399BDCAEF0729AA780
         [self.window.rootViewController.navigationController pushViewController:messageCtl animated:YES];
        
        if ([strTag isEqualToString:@"0"]) {
            
//            PerfectCarInfoVC1 * receive = [[PerfectCarInfoVC1 alloc]init];
//            [self.window.rootViewController presentViewController:receive animated:YES completion:nil];
            
        }else if ([strTag isEqualToString:@"1"]){
            

            
        }else{
//            NSNotification * Location = [NSNotification notificationWithName:@"push" object:nil ];
//            [[NSNotificationCenter defaultCenter] postNotification:Location];
//            
//            ReceiveViewController *messageCtl=[[ReceiveViewController alloc] init];
////            messageCtl.messageDic=_userInfoDic;
//            UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:messageCtl];
//            Nav.navigationBar.backgroundColor=[UIColor whiteColor];
//            
            
//            UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
            
//            RootViewController * root =(RootViewController*)self.window.rootViewController;
            
//            UIViewController *vc = topRootViewController;
//            while (vc.presentedViewController) {
//                vc = vc.presentedViewController;
//            }
//            while (vc.presentingViewController) {
//                UIViewController * tempVc = vc.presentingViewController;
//                [vc dismissViewControllerAnimated:NO completion:^{
//                }];
//                vc = tempVc;
//            }
            
//            NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
//            [pushJudge setObject:@"push"forKey:@"push"];
//            [pushJudge synchronize];
//            
//            [root.viewControllers[0] presentViewController:Nav animated:YES completion:nil];
            
//            UIApplication * app = [UIApplication sharedApplication];
//
//            if (app.applicationState != UIApplicationStateActive)
//            {
//                [self presentViewControllerWithUserInfo:userInfo];
//                
//            }
//            [self.window.rootViewController presentViewController:Nav animated:YES completion:nil];
            
         
        }
        
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif


- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

-(void)sendUUID{
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);
    CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
    if (![SSKeychain passwordForService:@"com.sandwish.eduOnline" account:@"user"]) {//查看本地是否存储指定 serviceName 和 account 的密码
        
        [SSKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr]
                     forService:@"com.sandwish.eduOnline"account:@"user"];
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user" ];
        //       NSLog(@"SSKeychain存储显示 :第一次安装过:%@", retrieveuuid);
        
        
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
    }else{
        
        //曾经安装过 则直接能打印出密码信息(即使删除了程序 再次安装也会打印密码信息) 区别于 NSUSerDefault
        
        
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user"];
        NSLog(@"SSKeychain存储显示 :已安装过:%@", retrieveuuid);
        
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
    }
}



@end
